<template>
  <view>
    <Header type="back" title="提交订单" />
    <view
      class="bg-f8ff py-2 w-100 px-2-6 ab left0 bottom0 rounded-right ov-hd-y"
      :class="'top' + toprpx"
    >
      <view class="w-100 px-2 pt-3 pb-4 f-s-c">
        <text
          class="w138 h66 f-c-c t-0 circle20 font24"
          @click="change_send_type(2)"
          :class="send_type == 2 ? 'bg-theme' : 'bg-dd'"
          >邮寄</text
        >
        <text
          class="w138 h66 f-c-c t-0 bg-dd circle20 font24 ml-3"
          @click="change_send_type(1)"
          :class="send_type == 1 ? 'bg-theme' : 'bg-dd'"
          >自提</text
        >
      </view>

      <view
        v-if="send_type == 1"
        class="font25 font600 t-20 px-3 f-b-c py-3 w-100 bg-white show0 circle34"
      >
        找工作人员领取
      </view>

      <view
        v-if="send_type == 2"
        class="px-3 f-b-c py-3 w-100 bg-white show0 circle34"
        @click="show_address()"
      >
        <view class="fs-y-s pr-8" v-if="address.id">
          <view class="f-b-c w-100 h50 pb-2">
            <view class="font32 font600 t-20">{{ address.name || "-" }}</view>
            <view class="font32 font600 t-20">{{ address.mobile || "-" }}</view>
          </view>
          <view class="font25 t-20">
            {{ address.province || "-" }}{{ address.city || "-"
            }}{{ address.county || "-" }}{{ address.address || "-" }}
          </view>
        </view>
        <view v-else class="font28">暂无地址</view>
        <view>
          <image src="../../static/icon_right_0.png" class="w40 h40" />
        </view>
      </view>

      <view class="w-100 h1 bg-ccc mt-5 mb-4"></view>
      <!-- <view class="w-100 py-3 px-2-4 font32 t-20">商品详情</view> -->
      <!-- <view class="w-100 h1 bg-ccc"></view> -->
      <view class="w-100 ov-hd circle32 show0">
        <view class="w-100 h106 bg-white">
          <view
            class="w-100 h-100 bg-theme f-y-c font26 font500 t-20 pl-4 radius-32-botton"
            >商品详情</view
          >
        </view>
        <view class="w-100 bg-theme">
          <view class="w-100 bg-white radius-32-right px-3 py-1">
            <view
              class="w-100 py-2 f-b-c ty-li"
              v-for="(item, index) in shop_car"
              :key="item.id"
            >
              <view class="f-b-c">
                <ImageFile
                  :url="item.thumbnail"
                  className="w142 h142 circle12"
                />
                <view class="pl-3 w500 fs-b-b h142">
                  <view class="font25 mt-1 t-20 font700 w-100">{{
                    item.name
                  }}</view>
                  <!-- <view class="font20 t-8 font400">汁汁双层嫩牛肉堡x1、百事(中)x1、冬阴功风味鸡翅x1</view> -->
                  <view class="f-b-c w-100">
                    <view class="font22 t-20 font500 mt-1">
                      ￥{{ item.price }}
                      <!-- <text class="font18 re ml-1 t-8 font400 t-del">￥160</text> -->
                    </view>
                    <view class="font25 t-20">
                      购买数量X{{ item.number }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- <Recommend :goodsType="goods_type" @get_recommend="set_recommend" /> -->

      <view class="w-100 px-2-4 pt-3">
        <!-- <view class="w-100 font28 t-20 font500 mb-5">商品小计</view>
				<view class="w-100 f-b-c mb-5 h24">
					<view class="font25 font400 t-20">积分抵扣：<text class="t-ed mx-06">-￥10.0</text>（消耗9000积分）</view>
					<view class="" @click="set_deduction">
						<image src="../../static/icon_select.png" class="w34 h34" v-show="!deduction"/>
						<image src="../../static/icon_select_cur.png" class="w34 h34" v-show="deduction"/>
					</view>
				</view> -->
        <view class="w-100 f-b-c mb-5 h24">
          <view class="font25 font400 t-20"
            >优惠券：
            <text class="t-ed mx-06" v-if="order_coupon.id"
              >-￥{{ order_coupon.money }}</text
            ></view
          >

          <view
            class="font25 t-0 f-y-c font600"
            @click="change_coupon()"
            v-if="order_coupon.id"
            >已选择
            <image src="../../static/icon_right_0.png" class="w24 h24" />
          </view>
          <view class="font25 t-3 f-y-c" v-else> 暂无可用优惠券 </view>
        </view>
      </view>
      <!-- 
			<view class="w-100 h1 bg-ccc"></view>
			
			<view class="w-100 f-b-c h24 px-2-4 py-3">
				<view></view>
				<view class="font28 t-0 font700"><text class="mx-06 pr-1 font400 font22">合计</text>￥{{order_info.money}}</view>
			</view> -->

      <view class="w-100 h273"></view>
    </view>
    <view class="w-100 fixed bottom0 pb-5 left0 z-999 option">
      <view class="w-100 px-4">
        <view class="w-100 f-b-c bg-theme_3 h100 circle120 pl-5">
          <view class="pl-1 font28 font700 t-w f-y-c">
            <text class="font24 font400 mr-05">合计</text>¥{{ shop_money }}
            <!-- <text class="font21 t-theme font500 mx-06 pl-1">已优惠￥{{order_info.coupon}}</text> -->
          </view>
          <view
            class="w220 h100 f-c-c bg-theme circle120 font28 font700 t-20"
            @click="get_purchass"
            >去支付</view
          >
        </view>
      </view>
    </view>

    <!-- 选择收货地址 开始 -->
    <uni-popup type="bottom" ref="popup_address" class="z-9999 re">
      <PopupHeader
        title="选择收货地址"
        @set_close="set_close('popup_address')"
        type="popup_address"
      >
        <template slot="popup_content">
          <view class="w-100 h16"></view>
          <view class="w-100 h408 re">
            <scroll-view
              class="scroll-view_H uni-scroll"
              scroll-y="true"
              scroll-with-animation
            >
              <view
                class="px-5 f-b-c py-3 border-bottom"
                v-for="(item, index) in address_list"
                :key="item.id"
                @click="change_address(item)"
              >
                <view class="fs-y-s pr-8">
                  <view class="f-b-c w-100 h50 pb-2">
                    <view
                      class="font32 font600"
                      :class="address.id == item.id ? 't-20' : 't-8'"
                      >{{ item.name }}</view
                    >
                    <view
                      class="font32 font600"
                      :class="address.id == item.id ? 't-20' : 't-8'"
                      >{{ item.mobile }}</view
                    >
                  </view>
                  <view
                    class="font25"
                    :class="address.id == item.id ? 't-20' : 't-8'"
                  >
                    {{ item.province }}
                    {{ item.city }}
                    {{ item.county }}
                    {{ item.address }}
                  </view>
                </view>
                <view>
                  <image
                    src="../../static/icon_select_cur.png"
                    v-if="address.id == item.id"
                    class="w40 h40"
                  />
                  <image
                    src="../../static/icon_select.png"
                    v-else
                    class="w40 h40"
                  />
                </view>
              </view>
              <view
                v-if="address_list.length == 0"
                class="w-100 py-6 font28 t-20 t-a"
                >暂无数据</view
              >
            </scroll-view>
          </view>
          <view class="w-100 h214 px-2-6 f-c-c">
            <view
              class="w-100 h100 f-c-c circle50 bg-theme font28 t-20 font700"
              @click="set_address"
              >添加收货地址</view
            >
          </view>
        </template>
      </PopupHeader>
    </uni-popup>
    <!-- 选择收货地址 END -->
  </view>
</template>

<script>
import { mapState, mapActions } from "vuex";
import Header from "../../components/header.vue";
import ImageFile from "../../components/img_file.vue";
import Recommend from "../../components/recommend.vue";
import PopupHeader from "./components/popup-header.vue";

import { address_list } from "../../api/mall.js";

import { order_submit } from "../../api/order.js";

import weixin_pay from "../../common/weixinPay.js";

export default {
  components: {
    Header,
    ImageFile,
    Recommend,
    PopupHeader,
  },
  mixins: [weixin_pay],
  data() {
    return {
      toprpx: 0,
      shop_show: false,
      deduction: false, //积分抵扣
      send_type: 1, //  // 寄送方式 1：自提/2：邮寄
      address_list: [],
      address: {},
      order_coupon: {},
    };
  },
  computed: {
    ...mapState("shop", ["shop_number", "shop_money", "shop_car"]),
  },
  onLoad(val) {
    this.address.id = val.address_id;
  },
  onShow() {
    setTimeout(() => {
      this.order_coupon = uni.getStorageSync("change_coupon") || {};
    }, 1000);
  },
  created() {
    this.get_my_coupon("MALL", this.shop_car);
    this.get_address_list();
  },
  mounted() {
    this.toprpx = uni.getStorageSync("toprpx");
    uni.$on("updateAdress", () => {
      this.get_address_list("update");
    });
  },
  onUnload() {
    uni.$off("updateAdress", () => {
      console.log("销毁监听");
    });
  },
  methods: {
    ...mapActions("shop", [
      "set_change_shop_shop_car",
      "set_clear_shop_shop_car",
    ]),

    change_coupon() {
      // 在weixinPay.js中默认选择优惠券时 存了当前选择的优惠券
      // 需要把当前价格传过去 进行筛选
      uni.navigateTo({
        url: `/pages/purchase/change_coupon?type=MALL&money=0&goods=${JSON.stringify(
          this.shop_car
        )}`,
      });
    },
    // 添加地址
    set_address() {
      uni.navigateTo({
        url: "/pages/shop/address",
      });
      this.$refs["popup_address"].close();
    },
    // 关闭弹出
    set_close(val) {
      this.$refs[val].close();
    },
    // 收货地址
    async get_address_list(type) {
      let query = {
        currentPage: 1,
        pageSize: 30,
      };
      const { body } = await address_list(query);
      this.address_list = body?.records || [];
      let address =
        body?.records?.find((item) => item.id == this.address?.id) || {};
      //页面返回更新地址时默认选中def || 第一项
      this.address =
        type === "update"
          ? body?.records?.find((item) => item.def) || body?.records[0]
          : address;
    },
    show_address() {
      this.$refs.popup_address.open();
    },
    // 选择地址
    change_address(val) {
      this.address = val;
      this.$refs.popup_address.close();
    },
    change_send_type(val) {
      this.send_type = val;
    },
    set_shop_show() {
      this.shop_show = !this.shop_show;
    },
    set_deduction() {
      this.deduction = !this.deduction;
    },

    // 设置订单信息
    set_goods_list(array) {
      const list = [];
      let totalFee = 0;
      let totalNum = 0;
      array?.map((item) => {
        list.push({
          activityPlanId: "", // 活动排班id 排班订单不能为空
          date: "", //预约日期 票务订单不能为空
          lineItemType: "", //路线类型 1：材料包/2：导览服务
          goodsId: item.id,
          goodsName: item.name,
          number: item.number,
          totalFee: item.number * item.price,
          unitFee: item.price,
        });
        totalFee += parseFloat((item.number * item.price).toFixed(2));
        totalNum += item.number;
      });
      return { list, totalFee, totalNum };
    },
    async get_purchass() {
      if (this.send_type == 2 && !this.address.id) {
        return uni.showToast({
          title: "请选择地址",
          icon: "none",
        });
      }
      const userInfo = uni.getStorageSync("userInfo") || {};
      const orgId = uni.getStorageSync("orgId") || "";

      let shop = this.set_goods_list(this.shop_car);

      let data = {
        orgId: orgId,
        payFee: shop.totalFee, // 支付金额
        remark: "",
        memberId: userInfo.id,
        payType: "WECHAT_PAY", //payType：支付类型 WECHAT_PAY:微信支付/MEMBER_CARD:会员卡支付
        subOrderList: [
          {
            addressId: this.address.id,
            couponFee: "",
            couponId: "",
            freightFee: 0, //运费
            goodsList: shop.list,
            payFee: shop.totalFee,
            orderType: "MALL", //shop shop,TICKET,YEAR_CARD,MALL,MAP ,LINE
            tableNo: "", // 桌号
            sendType: this.send_type, // 寄送方式 1：自提/2：邮寄
            totalFee: shop.totalFee,
            totalNum: shop.totalNum,
          },
        ],
      };

      const { code, body } = await order_submit(data);
      if (code === "0") {
        let id_list = body?.orderList.map((item) => item.id);
        let pay_info = {
          orderIdList: id_list, // 订单id集合
          payFee: shop.totalFee, // 支付金额
          id: id_list[0], //订单id
          payStatus: body.payStatus, // 支付状态 0元
          orderId: "MALL", //
        };
        // 去提交支付
        this.get_wx_order(pay_info, "shop");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.radius-32-botton {
  border-radius: 32rpx 32rpx 0 32rpx;
}
.radius-32-right {
  border-radius: 0 32rpx 0 0;
  .ty-li {
    border-top: 1rpx solid #ccc;
    &:first-child {
      border-top: none;
    }
  }
}
.t-del {
  &::after {
    content: "";
    width: 100%;
    height: 1rpx;
    background: #8a8a8a;
    position: absolute;
    top: 50%;
    left: 0;
  }
}
.ty-all {
  transform: rotate(90deg);
  transition: all 0.3s;
}
.ty-all-down {
  transform: rotate(270deg);
  transition: all 0.3s;
}
.hauto {
  height: auto !important;
  transition: all 0.3s;
}
.scroll-view_H {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 9;
}
.rounded-top-left-54 {
  border-radius: 54rpx 54rpx 0 0;
}
</style>
